#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSettings>
#include <QFileDialog>
#include <QString>
#include <QStandardItemModel>
#include "qcomm.h"
#include "xSceneView.h"
#include "xTreeView.h"
#include "qMeasureDialog.h"
#include "IUserEventCallBack.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    m_pTreeView(NULL),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    //设置central Widget 的layout
    QGridLayout* grid = new QGridLayout;
    grid->setContentsMargins(1,1,1,1);
    grid->setSpacing(0);
    ui->centralwidget->setLayout(grid);

    //初始化界面和回调
    initUi();

    m_pSceneView = new xSceneView(ui->centralwidget, m_pEventCall.get());
    grid->addWidget(m_pSceneView, 0, 0);

    //加载界面设置
    loadSettings();

    //更新ui
    updateUi();
}

MainWindow::~MainWindow()
{
    saveSettings();
    delete ui;
}

bool MainWindow::loadFile(const QString &file)
{
    if ( file.isEmpty() || !QFileInfo(file).exists() )
        return false;

    m_currFile = file;

    //打开场景
    m_pSceneView->openScene(file.toStdString());

    m_lastDirectory = QFileInfo(file).absolutePath();
    addRecentlyOpenedFile(m_currFile, m_recentFiles);
    setupRecentFilesMenu();

    return true;
}

void MainWindow::unloadAll()
{
    m_pSceneView->unloadAll();
}

void MainWindow::updateUi()
{
    //设置名字、版本、组织
     updateApplicationIdentity();

    // 最近的文件信号与槽 ...
    connect(ui->menuFile, SIGNAL(aboutToShow()), this, SLOT(setupRecentFilesMenu()));
    connect(ui->menuRecent_Files, SIGNAL(triggered(QAction*)), this,
            SLOT(recentFileActivated(QAction*)));

    // create tree m_pTreeModel
    m_pTreeView = new xTreeView(this);
    ui->dockWidget_Model->setWidget(m_pTreeView);

    //绑定场景和树形列表信号与槽
    connect(m_pSceneView, SIGNAL(sigAddFileToTree(const QString)), m_pTreeView, SLOT(slotAddFileToTree(const QString)), Qt::UniqueConnection);
    connect(m_pSceneView, SIGNAL(sigRemoveFileFromTree()), m_pTreeView, SLOT(slotRemoveAllFile()), Qt::UniqueConnection);
    connect(m_pTreeView, SIGNAL(sigTreeNodeSelected(QStandardItem*)), m_pSceneView, SLOT(slotCheckNode(QStandardItem*)), Qt::UniqueConnection);
}


void MainWindow::recentFileActivated(QAction *action)
{
    if (!action->text().isEmpty())
    {
        loadFile(action->text());
    }
}

void MainWindow::setupRecentFilesMenu()
{
    ui->menuRecent_Files->clear();

    if (m_recentFiles.count() > 0)
    {
        ui->menuRecent_Files->setEnabled(true);
        QStringList::Iterator it = m_recentFiles.begin();

        for (; it != m_recentFiles.end(); ++it)
             ui->menuRecent_Files->addAction(*it);
    }
    else
    {
         ui->menuRecent_Files->setEnabled(false);
    }
}

/*事件响应*/
void MainWindow::on_actionOpen_triggered()
{
    QString file = QFileDialog::getOpenFileName(this, "选择osgb索引", m_lastDirectory, "OSG 文件(*.osg *.osgb *.obj)");
    loadFile(file);
}

void MainWindow::on_actionUnload_triggered()
{
    unloadAll();
}

void MainWindow::on_actionSave_As_triggered()
{

}

void MainWindow::on_actionQuit_triggered()
{
    close();
}

void MainWindow::on_actionReset_View_triggered()
{
    m_pSceneView->home();
}

void MainWindow::on_actionTexture_triggered()
{
    m_pSceneView->setTextureEnable();
}

void MainWindow::on_actionLight_triggered()
{
    m_pSceneView->setLightEnable();
}

void MainWindow::on_actionHighLight_triggered()
{

}

void MainWindow::on_actionShadow_triggered()
{

}

void MainWindow::on_actionFull_Screen_triggered()
{

}

void MainWindow::saveSettings()
{
    QSettings settings(PACKAGE_ORGANIZATION, PACKAGE_NAME);

    settings.beginGroup("MainWindow");
    settings.setValue( "MainWindowState",saveState(0) );
    settings.setValue("size", size());
    settings.setValue("pos", pos());
    settings.setValue("fullScreen", isFullScreen());
    settings.endGroup();

    settings.beginGroup("Application");

    settings.setValue("lastDirectory", m_lastDirectory);

    // 最近文件
    settings.setValue("recentlyOpenedFiles", m_recentFiles);

    // scene background
    //settings.setValue( "bgcolor", ui->widgetSceneView->getBgColor() );

    settings.endGroup();
}


void MainWindow::loadSettings()
{
    QSettings settings(PACKAGE_ORGANIZATION, PACKAGE_NAME);

    settings.beginGroup("MainWindow");

    restoreState(settings.value("MainWindowState").toByteArray(), 0);

    resize(settings.value( "size", QSize(600, 600)).toSize());
    move(settings.value( "pos", QPoint(200, 200)).toPoint());

    bool fullScreen = settings.value("fullScreen",false).toBool();
    if (fullScreen)
        showFullScreen();
    settings.endGroup();

    settings.beginGroup("Application");
    m_lastDirectory = settings.value("lastDirectory","/home").toString();

    // 最近文件
    m_recentFiles = settings.value( "recentlyOpenedFiles").toStringList();

    // scene background
    //QColor color = settings.value( "bgcolor", QColor(50,50,50) ).value<QColor>();
    //ui->widgetSceneView->setBgColor(color);

    settings.endGroup();
}

void MainWindow::addRecentlyOpenedFile(const QString &fn, QStringList &lst)
{
    QFileInfo fi(fn);

    if ( lst.contains( fi.absoluteFilePath() ) )
        return;

    if ( lst.count() >= maxRecentlyOpenedFile )
        lst.removeLast();

    lst.prepend( fi.absoluteFilePath() );
}

void MainWindow::updateApplicationIdentity()
{
    QString strTitle = PACKAGE_NAME;
    strTitle += " ";
    strTitle += PACKAGE_VERSION;
    setWindowTitle(strTitle);
    QApplication::setApplicationName(PACKAGE_NAME);
    QApplication::setApplicationVersion(PACKAGE_VERSION);
    QApplication::setOrganizationName(PACKAGE_ORGANIZATION);
}

void MainWindow::initUi()
{
    //初始化测量对话框
    m_qmDialog = new qMeasureDialog(ui->centralwidget);

    //测量窗口回调接口
    IClosureNotifyMMsg* pNotifyMsg = m_qmDialog->getClosureNotifyMMsg();

    //创建回调类
    IEventCallBackFactory factory;
    m_pEventCall = factory.create(pNotifyMsg);
}

void MainWindow::on_actionFrontView_triggered()
{
    m_pSceneView->frontView();
}

void MainWindow::on_actionRearView_triggered()
{
    m_pSceneView->rearView();
}

void MainWindow::on_actionLeftView_triggered()
{
    m_pSceneView->leftView();
}

void MainWindow::on_actionRightView_triggered()
{
    m_pSceneView->rightView();
}

void MainWindow::on_actionLookUpView_triggered()
{
    m_pSceneView->lookUpView();
}

void MainWindow::on_actionLookDownView_triggered()
{
    m_pSceneView->lookDownView();
}

void MainWindow::on_actionMeasurePt_triggered()
{
    //显示测量窗口
    m_qmDialog->show();

    std::vector<OperatingState> vecOPS;
    vecOPS.push_back(OPS_DRAW_SINGLE_PT);
    vecOPS.push_back(OPS_MEASURE_POINT);
    //向浏览器发送消息进行激活!
    m_pSceneView->updateActivatedStatus(vecOPS);

}

void MainWindow::on_actionMeasureLine_triggered()
{
    //显示测量窗口
    m_qmDialog->show();

    std::vector<OperatingState> vecOPS;
    vecOPS.push_back(OPS_DRAW_SINGLE_LINE);
    vecOPS.push_back(OPS_MEASURE_LINE);
    //向浏览器发送消息进行激活!
    m_pSceneView->updateActivatedStatus(vecOPS);
}

void MainWindow::on_actionMeasureMulLine_triggered()
{
    //显示测量窗口
    m_qmDialog->show();

    std::vector<OperatingState> vecOPS;
    vecOPS.push_back(OPS_DRAW_MULTI_LINE_FOR_MULTI_LINE);
    vecOPS.push_back(OPS_MEASURE_MULTIlINE);
    //向浏览器发送消息进行激活!
    m_pSceneView->updateActivatedStatus(vecOPS);
}

void MainWindow::on_actionMeasureArea_triggered()
{
    //显示测量窗口
    m_qmDialog->show();

    std::vector<OperatingState> vecOPS;
    vecOPS.push_back(OPS_DRAW_MULTI_CLOSED_LINE_FOR_AREA);
    vecOPS.push_back(OPS_MEASURE_AREA);
    //向浏览器发送消息进行激活!
    m_pSceneView->updateActivatedStatus(vecOPS);
}
